//
//  ZTCareVideoTableViewController.m
//  zhibo8
//
//  Created by zzt on 16/11/21.
//  Copyright © 2016年 zzt. All rights reserved.
//

#import "ZTCareVideoTableViewController.h"
#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import "ZTCareitem.h"
#import "ZTCareVideoCell.h"

/**来播放视频⏬*/
#import "ZTVideoPlayer.h"
//#import <IJKMediaFramework/IJKMediaFramework.h>
/**来播放视频⏫*/

@interface ZTCareVideoTableViewController ()

@property (nonatomic, strong)NSMutableArray *modelArray;
@property (nonatomic, strong)NSString *url;
@property (nonatomic, strong)NSString *type;

@property (nonatomic, strong)ZTVideoPlayer *player;

//代理这里可以用weak,但是程序会提示错误,所以用retain
//@property(nonatomic, retain)id<IJKMediaPlayback>Play;
@property (nonatomic, strong)NSURL *starUrl;
@property (nonatomic, weak) UIView *MadieView;

//要用strong
@property (nonatomic, strong)UIViewController *backGroudVc;
@property (nonatomic, strong)UIButton *closeBtn;

@property (nonatomic, strong) AFHTTPSessionManager *mgr;

@property (nonatomic, strong) NSString *maxtime;
@end

static NSString * const ID = @"cell";
//////////////////////////
@implementation ZTCareVideoTableViewController

- (AFHTTPSessionManager *)mgr
{
    if (_mgr == nil) {
        _mgr = [AFHTTPSessionManager manager];
    }
    return _mgr;
}

- (NSString *)url{
    
//    NSDate *currentDate = [NSDate date];//获取当前时间，日期
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    
//    //只取年月日
//    [dateFormatter setDateFormat:@"YYYY/MMdd"];
//    
//    NSString *dateString = [dateFormatter stringFromDate:currentDate];
//    NSString *date = [NSString stringWithFormat:@"http://m.zhibo8.cc/m/ios/json/nba/%@-wdd.json",dateString];
//    return date;
    
    NSString *dateString = @"http://m.zhibo8.cc/m/ios/json/nba/2016/1123-wdd.json";
    return dateString;
   
}

- (NSString *)type{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
//    //只取年月日
//    [dateFormatter setDateFormat:@"YYYYMMddhhmmss"];
//    
//    NSString *dateString = [dateFormatter stringFromDate:currentDate];
//    return dateString;
    
    NSString *dateString = @"20161123213151";
    return dateString;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1.加载数据
//    [self loadData];
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"ZTCareVideoCell" bundle:nil] forCellReuseIdentifier:ID];
    
    self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 49, 0);
    
    
    // 添加上下拉刷新s
    [self setupRefreshView];
    
    // 请求更新数据
    [self.tableView.mj_header beginRefreshing];
    
    // 监听一次
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload) name:@"reloadTheme" object:nil];
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
}

- (void)reload {
    // 判断只有显示到屏幕上,才需要刷新
    // 只要当前控件能获取到窗口,就表示显示到屏幕
    if (self.view.window) {
        [self.tableView.mj_header beginRefreshing];
    }
}

#pragma mark - 添加上下拉刷新
- (void)setupRefreshView
{
    // 请求成功,一定要告诉MJRefresh,请求完成
    // 添加下拉刷新
    MJRefreshNormalHeader *headerView = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    headerView.automaticallyChangeAlpha = YES;
    self.tableView.mj_header = headerView;
    
    // 添加上拉刷新
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyHidden = YES;
    self.tableView.mj_footer = footer;
}

//********************************************************************
/*
//通过代理对象返回一个播放视频的view
- (void)setupMadieView {
    
    _backGroudVc = [[UIViewController alloc]init];
    _backGroudVc.view.frame = [UIScreen mainScreen].bounds;
    [self presentViewController: _backGroudVc animated:YES completion:nil];

    //通过代理对象view返回一个MadieView
    UIView *MadieView = [_Play view];
    _MadieView = MadieView;
    
    //横竖屏适配
    MadieView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    MadieView.frame = CGRectMake(0, 200, self.view.frame.size.width, 400);
    
    [ _backGroudVc.view addSubview:MadieView];
    
    _closeBtn = [[UIButton alloc] init];
    _closeBtn.frame = CGRectMake(20, 20, 40, 40);
    [_closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [_closeBtn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    
    [_backGroudVc.view addSubview:_closeBtn];
}

- (void)close {
    
    [_Play stop];
    [_Play pause];
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [_MadieView removeFromSuperview];

//    _Play = nil;

}
*/
//*************************************************************************
#pragma mark - 加载数据
- (void)loadNewData {
    
    // 取消上拉刷新
    [self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    //1.创建管理者
//    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    //2.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    parameters[@"type"] = @(41);
    
    //3.发送请求
    [self.mgr GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *responseObject) {
        
        // 结束刷新
        [self.tableView.mj_header endRefreshing];
        
        //1.获取字典数组
        NSArray *dictArray = responseObject[@"list"];
        
        //2.字典数组转模型数组
        _modelArray = [ZTCareitem mj_objectArrayWithKeyValuesArray:dictArray];
        
        //3.刷新表格
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
}

#pragma mark - 请求数据
- (void)loadMoreData
{
    // 取消下拉刷新
    [self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    // 2.拼接请求参数 默认是图片
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    // 只要想加载下一页的数据,需要传入上一页的maxtime
    parameters[@"maxtime"] = _maxtime;
    parameters[@"type"] = @(41);
    
    // 3.发送请求
    [self.mgr GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
        
        // 结束刷新
        [self.tableView.mj_footer endRefreshing];
        
        // 记录当前最大的_maxtime
        _maxtime = responseObject[@"info"][@"maxtime"];
        
        // 获取字典数组
        NSArray *dictArr = responseObject[@"list"];
        
        // 字典数组转模型数组
        NSArray *themes = [ZTCareitem mj_objectArrayWithKeyValuesArray:dictArr];
        
        // 模型数组转换成视图模型数组
        // 只要把模型转换层视图模型,对应cell子控件的位置和高度就计算完了
        for (ZTCareitem *item in themes) {
          
            [self.modelArray addObject:item];
        }
        
        // 刷新表格
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _modelArray.count;
}


- (ZTCareVideoCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZTCareVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    NSLog(@"%@",_modelArray[indexPath.row]);
    cell.item = _modelArray[indexPath.row];
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 49, 0);

    ZTCareitem *item = _modelArray[indexPath.row];
    
    ZTVideoPlayer *player = [[ZTVideoPlayer alloc] init];
    _player = player;
    
    [player videoWithString:item.videouri];
    
    
/*
    //电视直播
    _starUrl = [NSURL URLWithString:@"http://live.hkstv.hk.lxdns.com/live/hks/playlist.m3u8"];
    //创建一个播放器对象
    _Play = [[IJKFFMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:item.videouri] withOptions:nil];
    
    //通过代理对象返回一个播放视频的MadieView
    [self setupMadieView];
    
    //准备播放
    [_Play prepareToPlay];
    
    //开始播放
    [_Play play];
*/
    
}

@end

